using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace way.util
{
    public static class ConfigTool
    {
        static Configuration appConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        private static IConfiguration _configuration;
        public static void InitConfig()
        {
            if (_configuration != null) return;
            _configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsetting.json", optional: false, reloadOnChange: true)
                .Build();
        }
        public static string GetConnectionString(string connectionName) {
            if (_configuration==null) {InitConfig();}
            string connStr = _configuration[$"ConnectionStrings:{connectionName}"];
            if (string.IsNullOrWhiteSpace(connStr))
            {
                throw new ArgumentException($"appsetting.json not found {connectionName}");
            }
            return connStr;
        }
        public static string GetString(string keyPath)
        {
            if (_configuration==null) { InitConfig(); }
            return _configuration[keyPath];
        }
        public static T GetSection<T>(string sectionKey) where T : new()
        {
            if (_configuration == null) { InitConfig(); }
            var section = _configuration.GetSection(sectionKey);
            return section.Get<T>() ?? new T();
        }

        public static void setAppConfigSetting(string key,string context) {
            appConfig.AppSettings.Settings[key].Value = context;
            appConfig.Save(ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSetting") ;
        }
        public static string getAppConfigSetting(string key)
        {
            return appConfig.AppSettings.Settings[key].Value;
        }
    }
}
